/**
 * 
 * Copyright (C) 2015 by Elcom Software Company
 *
 * @id: FBPageFeed.java, May 8, 2015
 *
 */
package com.nip.fblike.grapapi.page;

import org.json.JSONArray;
import org.json.JSONObject;

import com.nip.fblike.grapapi.GraphAPIBase;
import com.nip.fblike.grapapi.IFBLike;
import com.nip.fblike.graphobject.page.FBPageFeedObject;
import com.nip.fblike.graphobject.page.FBPostObject;

/**
 * @author ThangNM<thangnm@elcom.com.vn>
 *
 * @version v
 */
public class FBPageFeed extends GraphAPIBase {

    /**
     * @param iFBLike
     */
    public FBPageFeed(IFBLike iFBLike) {
        super(iFBLike);
        // TODO Auto-generated constructor stub
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.nip.fblike.grapapi.IParserJson#parser(java.lang.String)
     */
    @Override
    public void parser(String json) {

        FBPageFeedObject object = new FBPageFeedObject();

        try {

            if(json == null || json.trim().isEmpty())
            {
                object.setEmpty(true);
                return;
            }
            
            JSONObject jsonObject = new JSONObject(json);
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            FBPostObject post;
            if (jsonArray != null && jsonArray.length() > 0) {
                long length = jsonArray.length();
                for (int i = 0; i < length; i++) {
                    if (!jsonArray.isNull(i)) {
                        post = new FBPostObject();
                        post.setId(safeReadString(jsonArray.getJSONObject(i),"id"));
                        post.setName(safeReadString(jsonArray.getJSONObject(i),"message"));
                        post.setLinks(safeReadString(jsonArray.getJSONObject(i),"link"));
                        post.setObject_id(safeReadString(jsonArray.getJSONObject(i),"object_id"));
                        post.setType(safeReadString(jsonArray.getJSONObject(i),"type"));
                        object.addPost(post);
                    }
                }
            }
        } catch (Exception e) {
            object.setEmpty(true);
        } finally {
            iFBLike.done(object);
        }

    }

    

    /*
     * (non-Javadoc)
     * 
     * @see com.nip.fblike.grapapi.GraphAPIBase#getUrl()
     */
    @Override
    public String getUrl() {
        // TODO Auto-generated method stub
        return "https://graph.facebook.com/" + getUid() + "/feed?access_token="
                + getAccess_token();
    }

}
